<?php

namespace Part02_StrategyMode\Code2;
use Exception;

/**
 * 假设3个商品，实际开发不可能这么传入，但问题不大，我们学的是设计模式不是业务。
 */
$goodsAName = $_POST['goodsAName'];
$goodsAPrice = $_POST['goodsAPrice'];
$goodsANum = $_POST['goodsANum'];
$chooseAType = $_POST['AType'];

$goodsBName = $_POST['goodsBName'];
$goodsBPrice = $_POST['goodsBPrice'];
$goodsBNum = $_POST['goodsBNum'];
$chooseBType = $_POST['BType'];

$goodsCName = $_POST['goodsCName'];
$goodsCPrice = $_POST['goodsCPrice'];
$goodsCNum = $_POST['goodsCNum'];
$chooseCType = $_POST['CType'];


$discountRange = [
    '正常价格',
    '打八折',
    '打七折',
    '打五折'
];
try {
    $totalA = getTotal($goodsAPrice, $goodsANum, $chooseAType);
    $totalB = getTotal($goodsBPrice, $goodsBNum, $chooseBType);
    $totalC = getTotal($goodsCPrice, $goodsCNum, $chooseCType);
} catch (Exception $e) {
    echo $e->getMessage();
    die;
}
$total = $totalA + $totalB + $totalC;

$list[$goodsAName] = [
    'price' => $goodsAPrice,
    'num' => $goodsANum,
    'total' => $totalA,
    'type' => $chooseAType,
];
$list[$goodsBName] = [
    'price' => $goodsBPrice,
    'num' => $goodsBNum,
    'total' => $totalB,
    'type' => $chooseBType,
];
$list[$goodsCName] = [
    'price' => $goodsCPrice,
    'num' => $goodsCNum,
    'total' => $totalC,
    'type' => $chooseCType,
];

foreach ($list as $goodsName => $data) {
    echo sprintf("%s：单价%d元,数量%d个,折扣情况【%s】总价%d元\n", $goodsName, $data['price'], $data['num'], $discountRange[$data['type']], $data['total']);
}
echo '总价为：' . $total . '元';


/**
 * @throws Exception
 */
function getTotal($price, $num, $type)
{
    switch ($type) {
        case null:
            throw new Exception('非法传入');
        case 0:
            return $price * $num;
        case 1:
            return $price * $num * 0.8;
        case 2:
            return $price * $num * 0.7;
        case 3:
            return $price * $num * 0.5;
        default:
            throw new Exception('非法传入');
    }
}

